package com.hougong.im.UDP;

import com.hougong.im.pool.ConnPool;
import com.hougong.im.transport.AcceptHandler;
import com.hougong.im.utils.JwtUtils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * 用来做内网穿透 UDP获取客户端的路由器上的端口
 */
public class UDPServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {
    private static final Logger LOGGER=LoggerFactory.getLogger(UDPServerHandler.class);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg)  {
        ByteBuf buf = msg.content();
        byte[] req = new byte[buf.readableBytes()];
        buf.readBytes(req);
        String token= null;
        try {
            token = new String(req,"UTF-8");
            LOGGER.info("收到消息udp token "+token);
            Long tokenUid = JwtUtils.getTokenUid(token);
            ConnPool.addUDP(tokenUid,msg.sender());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
    }
}
